import { Editor, IAllProps } from '@tinymce/tinymce-react';
import _ from 'lodash';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import styles from './TauRichEdit.module.scss';

interface TauRichEditor {
  value?: String;
  onChange?: (value: String) => void;
  editorProps: IAllProps;
}

const DEF_PROPS = {
  initialValue: '',
  init: {
    branding: false,
    language: global.LOCALE?.replace('-', '_'),
    skin: 'small',
    icons: 'small',
    height: 300,
    // inline: true,
    menubar: false,
    link_context_toolbar: false,
    // plugins: 'preview importcss searchreplace autolink autosave save directionality code visualblocks visualchars fullscreen image link media template codesample table charmap pagebreak nonbreaking anchor insertdatetime advlist lists wordcount help charmap quickbars emoticons accordion',
    plugins: [
      'advlist', 'lists', 'link', 'image', 'charmap',
      'anchor', 'searchreplace', 'visualblocks', 'code', 'fullscreen',
      'insertdatetime', 'media', 'table', 'preview', 'wordcount'
    ],
    toolbar: 'bold italic underline strikethrough | forecolor | blocks | align  bullist numlist | ' +
      'outdent indent | removeformat fullscreen',
    toolbar_mode: 'sliding',
    content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }',
    valid_elements: 'p[style],strong,em,span[style],a[href],ul,ol,li,h1[style],h2[style],h3[style],h4[style],h5[style],h6[style],&nbsp,br,s',
    valid_styles: {
      '*': 'font-size,font-family,color,text-decoration,text-align'
    },
    // powerpaste_word_import: 'clean',
    // powerpaste_html_import: 'clean',
    pad_empty_with_br: true,
    format_empty_lines: true,
  }
}

/**
 * 全局键值对选择器
 * @param {*} param0
 * @returns
 */
function TauRichEditor({ onChange, editorProps, ...props }: TauRichEditor) {
  const editorRef = useRef<Editor>(null);
  const [dirty, setDirty] = useState(false);
  const mergedProps = useMemo(() => _.defaultsDeep(editorProps, DEF_PROPS), [editorProps]);

  return (
    <div className={styles.tauRichEdit}>
      <Editor
        tinymceScriptSrc={'./tinymce/tinymce.min.js'}
        onInit={(evt, editor) => {
          return editorRef.current = editor;
        }}
        {...mergedProps}
        onDirty={() => setDirty(true)}
        onBlur={(e, editor) => {
          dirty && onChange?.(editor.getContent());
        }}
      />
    </div>
  );
}

export default TauRichEditor;
